package com.usian.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usian.mapper.AuthMapper;
import com.usian.mapper.RoleMapper;
import com.usian.mapper.UserMapper;
import com.usian.pojo.Auth;
import com.usian.pojo.Role;
import com.usian.pojo.User;
import com.usian.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.util.*;

@Service
public class UserService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AuthMapper authMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user =new User();
        Collection<GrantedAuthority> authorities = new ArrayList<>();  //存放用户角色和权限集合

        //根据用户名查询用户信息
        if (username != null) {

            //查询用户
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getUsername, username);
            user = userMapper.selectOne(lambdaQueryWrapper);
            if (user == null) {
                return null;
            }

            //查询角色  ROLE_admin  ROLE_sale

            List<Role> roles = roleMapper.findByUserId(user.getId());
            for (Role r : roles) {
                authorities.add(new SimpleGrantedAuthority("ROLE_" + r.getRoleName()));
            }

            //查权限
            List<Auth> authList = authMapper.findAuthByUserId(user.getId());
            for (Auth a : authList) {
                authorities.add(new SimpleGrantedAuthority(a.getName()));
            }
        }



        //结果封装到userDetail
        UserDetails userDetails = org.springframework.security.core.userdetails.User
                .withUsername(user.getUsername())
                .password(user.getPassword())
                .authorities(authorities).build();

        return userDetails;
    }


    public static void main(String[] args) {


        /*BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

        String encode = bCryptPasswordEncoder.encode("1234");
        System.out.println(encode);


        boolean b = bCryptPasswordEncoder.matches("1234", "$2a$10$isPr0H76ZanMsyw3RSW2VeDRWm7a/Mk6NEzqGj7g80n8VoRbbgnJy");
        System.out.println(b);*/


//        Map<String,String> map =new HashMap<>();
//        map.put("userid","6666");
//
//        String token = JWTUtils.getToken(map);
//        System.out.println(token);
//
//
//        DecodedJWT decodedJWT = JWTUtils.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2OTE3MzQ5NzAsInVzZXJpZCI6IjY2NjYifQ.dtwoaR7HruzKJVqb4GOuqParr02IoT-DXDyhuDMLGL8");
//
//        Claim userid = decodedJWT.getClaim("userid");
//        /*String aaa="";
//
//        User user = JSONObject.parseObject("aaa", User.class);*/
//
//        //System.out.println(JSON.toJSONString(decodedJWT));
//        System.out.println(JSON.toJSONString(decodedJWT.getClaim("userid").asString()));

        String url = "username=123&password=John";
        Map parameters = getParameters(url);
        JSONObject json = new JSONObject(parameters);
        System.out.println(json);

    }

    public static Map getParameters(String url) {
        Map parameters = new HashMap<>();
        try {
            //String[] parts = url.split("\\?");
            //String query = parts[1];
            for (String parameter : url.split("&")) {
                String[] pair = parameter.split("=");
                String key = URLDecoder.decode(pair[0], "UTF-8");
                String value = URLDecoder.decode(pair[1], "UTF-8");
                parameters.put(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return parameters;
    }
}
